package com.digitalchina.lxnsy.activity.management;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.FertilizerVO;
import com.digitalchina.lxnsy.entity.TestVO;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/24 11:45
 * 修改备注：
 * ================================================
 */
public class AddOutInActivity extends BaseActivity {

    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.et_weight)
    EditText etWeight;
    @Bind(R.id.et_total)
    EditText etTotal;
    @Bind(R.id.rb_fertilizer)
    RadioButton rbFertilizer;
    @Bind(R.id.rb_pesticide)
    RadioButton rbPesticide;
    @Bind(R.id.rg_sort)
    RadioGroup rgSort;
    @Bind(R.id.rb_in)
    RadioButton rbIn;
    @Bind(R.id.rb_out)
    RadioButton rbOut;
    @Bind(R.id.rg_status)
    RadioGroup rgStatus;
    @Bind(R.id.layout_total)
    RelativeLayout layoutTotal;
    @Bind(R.id.tv_weight_unit)
    TextView tvWeightUnit;

    private OptionsPickerView pvName, pvName2, pvType;
    private DatePickerDialog pvDate;

    private int mYear;
    private int mMonth;
    private int mDayOfMonth;

    private String materialType = "FERTILIZER"; // 默认化肥
    private String operationType = "ENTER"; // 操作类型 OUT 出库 ENTER 入库
    private String fertilizerPesticideId = ""; // 化肥或农药基础数据ID

    private List<FertilizerVO> fertilizerList;// 化肥
    private List<FertilizerVO> pesticidesList;// 农药

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_out_in);
        setTitle("农资出入库");
    }

    @Override
    public void initMember() {


        getFertilizerList();

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        pvDate = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                tvDate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        }, mYear, mMonth, mDayOfMonth);


        final List<TestVO> typeList = new ArrayList<>();
        for (int i = 0; i < Constant.specificationArray.length; i++) {
            typeList.add(new TestVO(Constant.specificationArray[i]));
        }

        pvType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvType.setText(typeList.get(options1).getPickerViewText());
            }
        })
                .setTitleText("规格")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvType.setPicker(typeList);
    }

    @Override
    public void addListener() {

        rgSort.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                if (radioGroup.getCheckedRadioButtonId() == R.id.rb_fertilizer) {
                    //化肥
                    tvWeightUnit.setText("总重量（kg）");
                    materialType = "FERTILIZER";
                } else {
                    //农药
                    tvWeightUnit.setText("总重量（ml）");
                    materialType = "PESTICIDE";
                }

                tvName.setText("");
                fertilizerPesticideId = "";
            }
        });

        rgStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (radioGroup.getCheckedRadioButtonId() == R.id.rb_in) {
                    //入库
                    layoutTotal.setVisibility(View.VISIBLE);
                    operationType = "ENTER";
                } else {
                    //出库
                    layoutTotal.setVisibility(View.GONE);
                    operationType = "OUT";
                }
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 保存
                        CustomDialog.nativeDialogFinish(activity, "保存成功");
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1:
                        callBack(message.obj);
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void callBack(Object object) {

        // 化肥
        fertilizerList = FastJsonUtil.getListBean(object.toString(), "fertilizerList", FertilizerVO.class);
        // 农药
        pesticidesList = FastJsonUtil.getListBean(object.toString(), "pesticidesList", FertilizerVO.class);


        // 化肥
        pvName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (fertilizerList == null || fertilizerList.size() == 0){
                    showToast("正在获取化肥，请稍候重试");
                    return;
                }

                tvName.setText(fertilizerList.get(options1).getPickerViewText());
                fertilizerPesticideId = fertilizerList.get(options1).getId();
            }
        })
                .setTitleText("化肥")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvName.setPicker(fertilizerList);

        // 农药
        pvName2 = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (pesticidesList == null || pesticidesList.size() == 0){
                    showToast("正在获取农药，请稍候重试");
                    return;
                }

                tvName.setText(pesticidesList.get(options1).getPickerViewText());
                fertilizerPesticideId = pesticidesList.get(options1).getId();
                tvWeightUnit.setText("总重量（" + pesticidesList.get(options1).getUnitMin() + "）");
            }
        })
                .setTitleText("农药")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvName2.setPicker(pesticidesList);


    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_date, R.id.layout_name, R.id.layout_type, R.id.bt_save})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_date:
                pvDate.show();
                break;
            case R.id.layout_name:
                if (pvName != null && pvName2 != null)
                    if (materialType.equals("FERTILIZER"))
                        pvName.show();
                    else
                        pvName2.show();
                else {
                    showToast("正在获取化肥");
                }
                break;
            case R.id.layout_type:
                if (pvType != null)
                    pvType.show();
                else {
                    showToast("正在获取规格");
                }
                break;
            case R.id.bt_save:
                save();
                break;
        }
    }

    private void save() {
        if (StringUtil.isTextEmpty(tvDate)) {
            showToast("请选择采购日期");
            return;
        }

        if (StringUtil.isTextEmpty(tvName)) {
            showToast("请选择化肥名称");
            return;
        }


        if (StringUtil.isTextEmpty(etWeight)) {
            showToast("请填写总重量");
            return;
        }

        if (StringUtil.isTextEmpty(tvType)) {
            showToast("请选择规格");
            return;
        }


        if (StringUtil.isTextEmpty(etNum)) {
            showToast("请填写数量");
            return;
        }

        if (rgStatus.getCheckedRadioButtonId() == R.id.rb_in && StringUtil.isTextEmpty(etTotal)) {
            showToast("请填写总金额");
            return;
        }

        /**
         * resNo	资源编号
         * enterpriseId	企业ID
         * operationDate	日期
         * materialType	类别 FERTILIZER 化肥 PESTICIDE 农药
         * fertilizerPesticideId	对应化肥或农药基础数据ID
         * operationType	操作类型 OUT 出库 ENTER 入库
         * weight	重量
         * specs	规格
         * number	数量
         * totalPrice	总金额
         */
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("operationDate", tvDate.getText().toString());
        params.put("materialType", materialType);
        params.put("fertilizerPesticideId", fertilizerPesticideId);
        params.put("operationType", operationType);
        params.put("weight", etWeight.getText().toString());
        params.put("specs", tvType.getText().toString());
        params.put("number", etNum.getText().toString());
        params.put("totalPrice", etTotal.getText().toString());

        OkHttpUtil.post(activity, URL.URL_ADD_STORAGE, "正在保存", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    // 农药 化肥  type = 0 化肥 type =1 农药 不传则取两种
    private void getFertilizerList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_FERTILIZER_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }
}
